package com.ljw.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description MyBatis工具类
 * @Author LJW
 * @Date 2023/3/29 23:28
 */
public class MyBatisUtil {

    private static SqlSessionFactory factory;

    static {    //通过静态代码块，唯一一次创建SQL Session Factory实例
        try {
            //获取对mybatis-config.xml的输入流
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            //加载MySQL连接
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            throw new RuntimeException("初始化失败", e);
        }
    }

    //创建并返回SQL Session实例
    public static SqlSession createSqlSession() {
        return factory.openSession(false);      //提交事务
    }

    //关闭SQL Session
    public static void closeSqlSession(SqlSession sqlSession) {
        if (sqlSession != null)
            sqlSession.close();
    }

}
